<template>
  <div class="app-container">
    <el-row class="app-row row" :gutter="20">
      <el-col class="app-col" :span="6">
        <el-row class="app-panel">
          <el-row style="margin-bottom: 20px">
            <el-col>
              <el-button size="mini" type="primary" @click="handleAdd">
                <i class="el-icon-plus"></i>
                新增
              </el-button>
            </el-col>
          </el-row>
          <el-tree :data="treeData" :props="defaultProps" class="treelable" @node-click="handleNodeClick" :highlight-current="true" :expand-on-click-node="false" ref="tree" :load="loadNode" lazy node-key="id">
            <span class="custom-tree-node" slot-scope="{ node }" style="width: 100%; font-size: 14px; line-height: 2em; display: flex; justify-content: space-between">
              <span>{{ node.label }}</span>
            </span>
          </el-tree>
        </el-row>
      </el-col>
      <el-col class="app-col" :span="18" v-loading="detailLoading">
        <el-row class="app-panel">
          <template v-if="formType !== 'empty'">
            <h3 v-if="formType === 'edit'" class="form-title">基本信息</h3>
            <h3 v-else class="form-title">新增部门</h3>
            <el-form size="mini" :model="formData" :rules="rules" ref="detailForm" label-position="right" label-width="140px">
              <el-form-item label="部门名称:" prop="name">
                <el-input clearable placeholder="请输入部门名称" style="width: 600px" v-model="formData.name"></el-input>
              </el-form-item>
              <el-form-item label="上级部门:" prop="parent">
                <el-input readonly clearable placeholder="无上级" style="width: 600px" v-model="formData.parent"></el-input>
              </el-form-item>
              <div class="tree-container">
                <div class="tree-no-parent" @click="handleNoParent">无上级</div>
                <el-tree :data="formTreeData" :props="defaultProps" class="treelable" @node-click="handleFormNodeClick" :highlight-current="true" :expand-on-click-node="false" ref="formTree" :load="loadNode" lazy node-key="id">
                  <span class="custom-tree-node" slot-scope="{ node }" style="width: 100%; font-size: 14px; line-height: 1.75em; display: flex; justify-content: space-between">
                    <span>{{ node.label }}</span>
                  </span>
                </el-tree>
              </div>
              <el-form-item label="是否开启:" prop="status">
                <el-switch v-model="formData.status" inactive-text="否" active-text="是"> </el-switch>
              </el-form-item>
            </el-form>
            <el-row v-if="formType === 'edit'">
              <p class="form-desc">最新修改时间: {{ formData.created_time }}</p>
            </el-row>
            <!-- 按钮 -->
            <div v-if="formType === 'edit'" class="bottom-buttons">
              <el-button size="mini" @click="handleDelete" type="danger">删除</el-button>
              <el-button size="mini" @click="handleSave" type="primary">保存</el-button>
            </div>
            <div v-else class="bottom-buttons">
              <el-button size="mini" @click="handleCancel">取消</el-button>
              <el-button size="mini" @click="handleAddSave" type="primary">保存</el-button>
            </div>
          </template>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { apiDepartmentList, apiDepartmentDetail, apiDepartmentAdd, apiDepartmentEdit, apiDepartmentDelete } from '@/api/system'
import SelectTree from './select-tree'
export default {
  components: { SelectTree },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'leaf',
      },
      current: null,
      treeData: [], //tree列表
      detailLoading: false,
      formType: 'empty', // 添加:'add'，编辑:'edit'
      formData: {
        name: '',
        parent: '',
        parentId: '',
        oldParentId: '',
        status: true,
      },
      formDataEmpty: {
        name: '',
        parent: '',
        parentId: '',
        oldParentId: '',
        status: true,
      },
      rules: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
      },
    }
  },
  computed: {
    formTreeData: () => {
      return []
    },
  },
  watch: {},
  mounted() {},
  methods: {
    // 展开获取子部门
    loadNode(node, resolve) {
      if (node.level === 0) {
        apiDepartmentList({ id: '' }).then((res) => {
          if (res.code === 200) {
            const list = this.formatTreeData(res.data.data)
            // 获取第一个部门信息并展示
            if (this.formType === 'empty' && list.length > 0 && list[0].id) {
              this.$refs.tree.setCurrentKey(list[0].id)
              this.current = list[0]
              this.getDetail(list[0])
            }
            return resolve(list)
          }
        })
      } else {
        apiDepartmentList({ id: node.data.id }).then((res) => {
          if (res.code === 200) {
            const list = this.formatTreeData(res.data.data)
            return resolve(list)
          }
        })
      }
    },
    // 更新部门列表
    updateTree({ type, id, parentId, oldParentId, data }) {
      if (type === 'add') {
        // 添加，直接再parentid追加节点
        this.$refs.tree.append(data, parentId)
        this.$refs.formTree.append(data, parentId)
      } else if (type === 'update') {
        // 更新,删除原节点，parentid追加节点
        this.$refs.tree.getNode(id).data = data
        if (parentId !== oldParentId) {
          // 移动
          const node = this.$refs.tree.getNode(id)
          this.$refs.tree.remove(id)
          this.$refs.tree.append(data, parentId)
          this.$refs.formTree.remove(id)
          this.$refs.formTree.append(data, parentId)
        }
      } else if (type === 'delete') {
        this.$refs.tree.remove(id)
        this.$refs.formTree.remove(id)
      }
    },
    // 格式化部门数据
    formatTreeData(list) {
      list.forEach((item) => {
        item.leaf = parseInt(item.is_have_child) === 1 ? false : true
      })
      return list
    },
    // 新增部门-新增
    handleAdd() {
      this.formData = { ...this.formDataEmpty }
      if (this.current) {
        this.formData.parent = this.current.name
        this.formData.parentId = this.current.id
      }
      this.formType = 'add'
    },
    // 新增部门-取消
    handleCancel() {
      this.formData = { ...this.formDataEmpty }
      this.formType = 'empty'
    },
    // 新增部门-保存
    handleAddSave() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          this.detailLoading = true
          apiDepartmentAdd(this.formatSendData()).then((res) => {
            this.detailLoading = false
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '新增成功!',
              })
              this.formType = 'edit'
              // 更新父节点的子节点
              this.getDetail({ id: res.data.id })
              this.updateTree({ type: 'add', data: { id: res.data.id, name: this.formData.name, leaf: true, parent_id: this.formData.parentId, is_have_child: false }, parentId: this.formData.parentId })
            }
          })
        } else {
          return false
        }
      })
    },
    // 无上级
    handleNoParent() {
      this.formData.parent = ''
      this.formData.parentId = ''
      this.$refs.formTree.setCurrentKey(null)
    },
    // 格式化接口发送数据
    formatSendData() {
      return {
        name: this.formData.name,
        parent_id: this.formData.parentId,
        status: this.formData.status ? 1 : 0,
      }
    },
    // 编辑信息-删除
    handleDelete() {
      this.$confirm('此操作将删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.deleteConfirm()
      })
    },
    // 编辑信息-删除确认
    deleteConfirm() {
      this.detailLoading = true
      apiDepartmentDelete({ id: this.current.id }).then((res) => {
        this.detailLoading = false
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          this.formType = 'empty'
          this.updateTree({ type: 'delete', id: this.current.id })
          this.current = null
        }
      })
    },
    // 编辑信息-保存
    handleSave() {
      this.$refs.detailForm.validate((valid) => {
        if (valid) {
          this.detailLoading = true
          apiDepartmentEdit(Object.assign({ id: this.current.id }, this.formatSendData())).then((res) => {
            this.detailLoading = false
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '保存成功!',
              })
              // 更新新老父节点的子节点
              const nodeData = this.$refs.tree.getNode(this.current.id).data
              this.updateTree({
                type: 'update',
                id: this.current.id,
                parentId: this.formData.parentId,
                oldParentId: this.formData.oldParentId,
                data: Object.assign(nodeData, this.formatSendData()),
              })
              this.formData.oldParentId = this.formData.parentId
            }
          })
        } else {
          return false
        }
      })
    },
    // tree点击事件
    handleNodeClick(data) {
      this.current = data
      this.getDetail(data)
    },
    // 表单tree点击事件
    handleFormNodeClick(data) {
      if (data.id === this.current.id) {
        this.$message({
          type: 'error',
          message: '不能选择本部门为上级部门',
        })
        this.$refs.formTree.setCurrentKey(null)
        return
      }
      this.formData.parent = data.name
      this.formData.parentId = data.id
    },
    // 获取部门详情
    getDetail(data) {
      this.detailLoading = true
      apiDepartmentDetail({ id: data.id })
        .then((res) => {
          this.detailLoading = false
          if (res.code === 200) {
            const { name, parent_name, status, parent_id, created_time } = res.data
            this.formData.name = name
            this.formData.parent = parent_name
            this.formData.parentId = parent_id
            this.formData.oldParentId = parent_id
            this.formData.status = status === 1 ? true : false
            this.formData.created_time = created_time
            this.formType = 'edit'
          }
        })
        .catch((e) => {
          this.detailLoading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.treelable {
  padding-right: 20px;
}

::v-deep .treelable .el-tree-node__content {
  height: 35px;
}
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  color: #409eff;
  background: none;
}

.app-container {
  height: calc(100vh - 50px - 34px);
  background: #f2f2f2;
  .app-row,
  .app-col {
    height: 100%;
  }
  .app-panel {
    position: relative;
    height: 100%;
    background: #ffffff;
    padding: 30px;
    border-radius: 4px;
  }
}
.form-title {
  margin-bottom: 40px;
}
.form-desc {
  font-size: 14px;
  color: #aaa;
  padding-left: 67px;
}
.bottom-buttons {
  position: absolute;
  bottom: 30px;
  right: 30px;
}
.tree-container {
  width: 600px;
  height: 300px;
  margin-bottom: 20px;
  margin-left: 140px;
  overflow: hidden;
  overflow-y: scroll;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  .tree-no-parent {
    height: 35px;
    line-height: 35px;
    font-size: 14px;
    color: #606266;
    padding-left: 24px;
    cursor: pointer;
    &:hover {
      background: #f5f7fa;
    }
  }
}
</style>
